#include "Model.h"

Model * Model::instance;

Model::Model(void)
{
	passiveObjects.reserve(2048);
	passiveObjects.assign(2048, NULL);
	activeObjects.reserve(1024);
	activeObjects.assign(1024, NULL);

	gravity = new b2Vec2(0, 1);
	world = new b2World( *gravity, true);

	instance = this;
	//Tracer::trace("model constructed");
}

Model::~Model(void)
{
}

BITMAP * Model::loadToVid(BITMAP * bmp)
{
	BITMAP *temp;
	temp = create_video_bitmap (bmp->w, bmp->h);
	if (temp)
	{
		blit (bmp, temp, 0, 0, 0, 0, bmp->w, bmp->h);
		destroy_bitmap (bmp);
		bmp = temp;
	}
	return bmp;
}

void Model::parseDataFile(const char *name)
{
	int i;
	data = load_datafile(name);
	if(!data)
	{
		allegro_message("Unable to load data file!");
		return;
	}
	for (i = 0; data[i].type != DAT_END; i++)
	{
		if (data[i].type == DAT_BITMAP)
			data[i].dat = loadToVid( (BITMAP*)data[i].dat );
	}
}


void Model::addListener(FatBase<void> *ls)
{
	listeners.push_back(ls);
}


void Model::sendMessage(GameObject *& o)
{
	unsigned int i =0;
	for(i = 0; i < listeners.size(); i++)
	{
		listeners[i]->callMethod(&o);
	}
}

GameObject *& Model::addActiveObject(GameObject *o)
{
	std::vector <GameObject *>::iterator it;
	it = find(activeObjects.begin(), activeObjects.end(), (GameObject *)NULL);
	*it = o;
	sendMessage(*it);

	return (*it);
}

GameObject *& Model::addPassiveObject(GameObject *o)
{
	std::vector <GameObject *>::iterator it;
	it = find(passiveObjects.begin(), passiveObjects.end(), (GameObject *)NULL);
	*it = o;
	sendMessage(*it);
	
	return (*it);
}